import React, { ReactElement, useRef, useState, useEffect } from 'react';
import { Button, message, Tree } from 'antd';
import { getMenu } from '@/api/menu';
import { getMenuByRoleId } from '@/api/role';
import ProForm, {
  DrawerForm,
  ProFormText,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-form';
// import { PlusOutlined } from '@ant-design/icons';
import { updateRole } from '@/api/role';

interface Props {
  reload: () => void;
  record: any;
  visible: boolean;
  close: () => void;
}
export default function UpdateRole({
  reload,
  record,
  close,
  visible,
}: Props): ReactElement {
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const formRef = useRef();

  useEffect(() => {
    console.log(record, 'fffff');
    // form.setFieldsValue(record)
    console.log(visible);
  }, [record.roleId]);

  const [treeData, setTreeData] = useState<any[]>([]);
  const getMenus = async () => {
    const res = await getMenu();

    if (res.status == 200) {
      // console.log(res.data.rows.children, 'menu');
      setTreeData([...res.data.rows.children]);
    }
  };
  const getMenuByRoleIdAsync = async () => {
    const res = await getMenuByRoleId(record.roleId);
    // console.log(res, 'resmenus');
    if (res.status == 200) {
      setCheckedKeys(res.data);
    }
  };

  // getMenus();
  // getMenuByRoleIdAsync()
  // interface IAdd {
  //   roleName: string; //	角色名称
  //   remark?: string; //角色描述
  //   menuId: string; //	菜单 ID（例如：1,2,58）
  // }
  interface IValue {
    roleName: string; //	角色名称
    remark?: string; //角色描述
  }
  const updateRoleAsync = async (values: IValue) => {
    const data = {
      roleId: record.roleId.toString(),
      ...values,
      menuId: checkedKeys.toString(),
    };
    console.log(data);

    const res = await updateRole(data);
    if (res.status == 200) {
      close();
      reload();
      message.success('修改角色成功');
    } else {
      message.error('修改角色失败');
    }
  };

  const onCheck = (checkedKeysValue: any) => {
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };
  return record.roleId ? (
    <DrawerForm<{
      roleName: string;
      company: string;
    }>
      width={500}
      title="修改角色"
      formRef={formRef}
      // trigger={<SettingOutlined key="editable" style={{ color: '#4A9FF5' }} />}
      visible={visible}
      onVisibleChange={async (visible) => {
        if (visible) {
          await getMenus();
          getMenuByRoleIdAsync();
        } else {
          close();
        }
      }}
      autoFocusFirstInput
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        // await waitTime(2000);
        const data = await updateRoleAsync(values);
        console.log(data, 'data');
        // message.success('提交成功');
        // 不返回不会关闭弹框
        return true;
      }}
      initialValues={record}
    >
      <ProFormText
        name="roleName"
        width="md"
        label="角色名称："
        tooltip="最长为 24 位"
        placeholder="请输入名称"
      />
      <ProFormTextArea
        width="md"
        name="remark"
        label="角色描述"
        placeholder="请输入名称"
      />
      <ProFormSelect label="权限选择">
        <Tree
          checkable
          // onExpand={onExpand}
          // expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
          treeData={treeData}
        />
      </ProFormSelect>
    </DrawerForm>
  ) : (
    <></>
  );
}
